import re
from django.shortcuts import render,redirect
from .models import BookmarkerModelForm,BookmarkerModel,DomainZoneModel,DomainZoneModelForm,BookmarkerFileModelForm

#访问云书签主页 url列表页
def goBookmarkerPage(request):
    form = BookmarkerModelForm()
    uploadForm = BookmarkerFileModelForm()
    bookmarkersByDomainZone = DomainZoneModel.objects.all()
    content = {'form':form,'list':bookmarkersByDomainZone,'uploadForm':uploadForm}
    return render(request,'bookmarker.html',content)

#单个书签新增与修改
def editBookmarker(request):
    bookmarker = BookmarkerModelForm(request.POST)
    domainZone = DomainZoneModelForm(request.POST)
    dz = DomainZoneModel.objects.filter(domain=request.POST.get('domain'))
    if len(dz) < 1:
        dz = domainZone.save()
    else:
        dz = dz[0]
    bm = bookmarker.save(commit=False)
    bm.domainZone = dz
    bm.save()
    return redirect('/bookmarker/')

#删除书签
def deleteBookmarker(request,entryType,entryId):
    if entryType == 'bm' :
        bm = BookmarkerModel.objects.get(pk=entryId)
        bm.delete()
    elif entryType == 'domain' :
        domain = DomainZoneModel.objects.get(pk=entryId)
        domain.delete()
    return redirect('/bookmarker/')

#上传导出的书签文件
def uploadFile(request):
    if request.method == 'POST':
        form = BookmarkerFileModelForm(request.POST,request.FILES)
        if form.is_valid():
            uploadFile = request.FILES['uploadFile']
            #handleUploadedFile(uploadFile,'C:/E\codes/python/mydjango/website/yunbookmarker/static/upload/'+uploadFile.name)
            form.save()
            with open('media/yunbookmarker/static/uploads/'+uploadFile.name,'r',encoding='utf-8') as f :
                parseBookmarkerHtmlFile(f.read())
    return redirect('/bookmarker/')


def handleUploadedFile(f,targetFile):
    with open(targetFile,'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

def parseBookmarkerHtmlFile(html:str):
    links = re.findall('<A HREF="(.*?)" ADD_DATE=".*?"( ICON=".*?"?){0,1}>(.*?)</A>',html)
    print(len(links))